// @ts-nocheck
import router from '@system.router'
import data_distributedData from '@ohos.data.distributedData';
import distributedHardware_deviceManager from '@ohos.distributedHardware.deviceManager';
import commonEvent from '@ohos.commonEvent';
import {Core, ExpectExtend, ReportExtend, InstrumentLog} from 'deccjsunit/index';
import file from '@system.file';
import featureAbility from '@ohos.ability.featureAbility';
import bundle from '@ohos.bundle';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';

let kvManager,kvStore,devManager;
const bundle_name = 'com.example.myapplicationsectest';

export default {
    data: {
        logText: '',
        deviceList:[],
        syncMode: data_distributedData.SyncMode.PUSH_ONLY,
        store_id:'myapplicationsectest_storeid',
        subscribeType: 2,
        dataListenerStarted: false,
        syncListenerStarted: false,
        securityLevel: data_distributedData.SecurityLevel.NO_LEVEL,
    },
    onInit() {
        this.grantpermission();
        this.logText = '';
        kvManager = null;
        kvStore = null;
        devManager = null;
    },
    onShow() {
//        console.log('securityTest:onShow')
//        const core = Core.getInstance()
//        const expectExtend = new ExpectExtend({
//            'id': 'extend'
//        })
//        const reportExtend = new ReportExtend(file)
//        core.addService('expect', expectExtend)
//        core.addService('report', reportExtend)
//        core.init()
//        core.subscribeEvent('task', reportExtend)
//
//        const configService = core.getDefaultService('config')
//        configService.setConfig(this)
//        require('../../../test/List.test')
//        core.execute()
//
//        console.log('securityTest:onShow finished')
    },
    onReady() {
    },
    onDestroy(){
        if( kvStore != null) {
            this.stopDataListener();
            this.stopSyncListener();
        }
        this.logText = '';
        this.release();
    },
    release() {
        if (devManager != null) {
            devManager.off('deviceStateChange');
            devManager.off('serviceDie');
            devManager.release();
        }
    },
    async grantpermission() {
        console.info('zjj grantpermission');
        let context = featureAbility.getContext();
        let bundleFlag = 0;
        let tokenId = undefined;
        let userId = 100;
        let appInfo = await bundle.getApplicationInfo('com.example.myapplicationsectest', bundleFlag, userId);
        tokenId = appInfo.accessTokenId;
        console.info('zjj tokenId=${tokenId}');
        let atManager = abilityAccessCtrl.createAtManager();

        let result = await atManager.verifyAccessToken(tokenId, 'ohos.permission.DISTRIBUTED_DATASYNC');
        console.info('zjj result=${result}');

        if (result == abilityAccessCtrl.GrantStatus.PERMISSION_DENIED) {
            console.info('zjj result=PERMISSION_DENIED');
            context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function(result) {
                console.info('zjj result.requestcode=${result.requestCode}');
            })
        }

    },
    CreateDevManager() {
        if (devManager != null) {
            console.info('[JSDemo] devManager already created');
            this.logText += "devManager already created.\r\n";
            return;
        }
        distributedHardware_deviceManager.createDeviceManager("com.example.myapplicationsectest", (error, value) => {
            if (error) {
                console.error("createDeviceManager failed.");
                this.logText += "createDeviceManager failed.\r\n";
                return;
            }
            devManager = value;
            this.logText += "createDeviceManager success.\r\n";
            devManager.on('deviceStateChange', (data) => {
                this.logText += "deviceStateChange on: " + JSON.stringify(data) + ".\r\n";
                console.info("deviceStateChange on:" + JSON.stringify(data));
            });

            devManager.on('serviceDie', () => {
                this.logList.push("serviceDie on:");
                this.logText += "serviceDie on: " + ".\r\n";
                console.info("serviceDie on:");
            });
        });
    },
    GetDevList() {
        if(devManager != null) {
            var array = devManager.getTrustedDeviceListSync();
            //            this.logText += "array: " + JSON.stringify(array) + ".\r\n";
            //            console.info("array: " + JSON.stringify(array));
            //            var local = devManager.getLocalDeviceInfoSync();
            //            this.logText += "local: " + JSON.stringify(local) + ".\r\n";
            //            console.info("local: " + JSON.stringify(local));
            //            var filterStr = "{\"filters\":[{\"commonFilter\":{\"groupType\":\"1\",\"curComType\" :4}}]}";
            //            let options = {
            //                "targetPkgName": "com.example.jsdistributedatademo",
            //                "sortType": 0,
            //                "filter": filterStr
            //            }
            //            devManager.getTrustedDeviceList(options, (err, data) => {
            //                if (err) {
            //                    return;
            //                }
            //                var arr = data;
            //                this.logText += "arr: " + JSON.stringify(arr) + ".\r\n";
            //                console.info("arr: " + JSON.stringify(arr));
            //            });
            var list = new Array();
            console.info('[JSDemo] getTrustedDeviceListSync, count=' + array.length);
            for (var i = 0; i < array.length; i++) {
                console.info('[JSDemo] device ' + (i+1)  + '/' + array.length +
                ' deviceId=' + array[i].deviceId + ' deviceName=' + array[i].deviceName
                + ' deviceType=' + array[i].deviceType);
                list[i] = array[i].deviceId;
            }
            this.deviceList = list;
        }
    },
    CreateKVManager() {
        this.CreateDevManager();
        console.info("[JSDemo] CreateKVManager begin");
        if (kvManager != null) {
            console.info('[JSDemo] kvManager already created');
            this.logText += "kvManager already created.\r\n";
            return;
        }
        try {
            const config = {
                bundleName : bundle_name,
                userInfo : {
                    userId : '0',
                    userType : 0
                }
            }
            const promise = data_distributedData.createKVManager(config);
            promise.then((manager) => {
                if (manager == null) {
                    console.info("[JSDemo] CreateKVManager createKVManager fail ");
                    return;
                }
                kvManager = manager;
                //                kvManager.GetDeviceList()
                console.info("[JSDemo] CreateKVManager createKVManager success " + manager);
                this.logText += "CreateKVManager success.\r\n";
            }).catch((err) => {
                console.info("[JSDemo] createKVManager createKVManager err " + err);
                this.logText += "CreateKVManager err " + err + ".\r\n";
            });
        } catch (e) {
            console.log("[JSDemo] createKVManager e " + e);
            this.logText += "CreateKVManager e " + e + ".\r\n";
        }
    },
    GetKVStore() {
        console.info("[JSDemo] GetKVStore begin");
        if(kvManager == null) {
            console.info('[JSDemo] GetKVStore kvManager is null');
            this.logText += "GetKVStore kvManager is null.\r\n";
            return;
        }
        if(kvStore != null) {
            console.info('[JSDemo] kvStore already created');
            this.logText += "kvStore already created.\r\n";
            return;
        }
        try {
            const options = {
                createIfMissing : true,
                encrypt : true,
                backup : false,
                autoSync : false,
                kvStoreType : 1,
                schema : '',
                securityLevel : this.securityLevel
            }
            const promise = kvManager.getKVStore(this.store_id, options);
            promise.then((store) => {
                if (store == null) {
                    console.info("[JSDemo] CreateKVManager createKVManager fail ");
                    return;
                }
                kvStore = store;
                console.log("[JSDemo] GetKVStore getKVStore success " + store);
                this.logText += "GetKVStore success.\r\n";
                this.logText += "GetKVStore success securityLevel:" + this.securityLevel + "kvStoreType:1.\r\n";
            }).catch((err) => {
                console.log("[JSDemo] GetKVStore getKVStore err " + err);
                this.logText += "GetKVStore err " + err + ".\r\n";
            });
        } catch (e) {
            console.log("[JSDemo] GetKVStore e " + e);
            this.logText += "GetKVStore e " + e + ".\r\n";
        }
    },
    DeleteKvStore () {
        console.info("[JSDemo] DeleteKvStore begin");
        if(kvManager == null) {
            console.info('[JSDemo] DeleteKvStore kvManager is null');
            this.logText += "DeleteKvStore kvManager is null.\r\n";
            return;
        }
        if(kvStore == null) {
            console.info('[JSDemo] kvStore already remove');
            this.logText += "kvStore already remove.\r\n";
            return;
        }
        try {
            kvManager.closeKVStore('com.example.myapplicationsectest', this.store_id, kvStore).then(() => {
                console.log('closeKVStore success');
                this.logText += "closeKVStore success.\r\n";
            }).catch((err) => {
                console.log('closeKVStore err');
                this.logText += "closeKVStore success.\r\n";
            });
            kvManager.deleteKVStore('com.example.myapplicationsectest', this.store_id).then(() => {
                console.log('deleteKVStore success');
                kvStore = null;
                kvManager = null;
                this.logText += "deleteKVStore success.\r\n";
            }).catch((err) => {
                console.log('deleteKVStore err ' );
                this.logText += "deleteKVStore fail.\r\n";
            });
//            const promise = kvManager.closeAllKVStore(bundle_name);
//            promise.then((status) => {
//                console.log("RemoveAllStore closeAllKVStore success " + status);
//                const promise1 = kvManager.deleteAllKVStore(bundle_name);
//                promise1.then((status) => {
//                    console.log("RemoveAllStore deleteAllKVStore success " + status);
//                    kvStore = null;
//                    this.stopDataListener();
//                    this.stopSyncListener();
//                    this.logText += "RemoveAllStore success.\r\n";
//                }).catch((err) => {
//                    console.log("RemoveAllStore deleteAllKVStore fail " + err);
//                    this.logText += "RemoveAllStore deleteAllKVStore err " + err + ".\r\n";
//                });
//            }).catch((err) => {
//                console.log("RemoveAllStore closeAllKVStore fail " + err);
//                this.logText += "RemoveAllStore closeAllKVStore fail " + err + ".\r\n";
//            });
        } catch (e) {
            console.log("[JSDemo] RemoveAllStore e " + e);
            this.logText += "RemoveAllStore e " + e + ".\r\n";
        }
    },
    GetSecurityLevel() {
        if(kvStore == null) {
            console.info('[JSDemo] kvStore is null');
            this.logText += "kvStore is null.\r\n";
            return;
        }
        try {
            kvStore.getSecurityLevel().then((data) => {
                console.log(' getSecurityLevel success');
                switch(data) {
                    case data_distributedData.SecurityLevel.NO_LEVEL:
                        this.logText += "getSecurityLevel success: NO_LEVEL.\r\n";
                        break;
                    case data_distributedData.SecurityLevel.S0:
                        this.logText += "getSecurityLevel success: S0.\r\n";
                        break;
                    case data_distributedData.SecurityLevel.S1:
                        this.logText += "getSecurityLevel success: S1.\r\n";
                        break;
                    case data_distributedData.SecurityLevel.S2:
                        this.logText += "getSecurityLevel success: S2.\r\n";
                        break;
                    case data_distributedData.SecurityLevel.S3:
                        this.logText += "getSecurityLevel success: S3.\r\n";
                        break;
                    case data_distributedData.SecurityLevel.S4:
                        this.logText += "getSecurityLevel success: S4.\r\n";
                        break;
                    default:
                        this.logText += "getSecurityLevel success: NO_LEVEL.\r\n";
                }
            }).catch((err) => {
                console.log('getSecurityLevel fail ' + JSON.stringify(err));
                this.logText += "getSecurityLevel fail" + JSON.stringify(err) + ".\r\n";
            });
        }catch(e) {
            console.log('GetSecurityLevel e ' + e);
        }
    },
    SetSecurityLevel() {
        this.$element('securityLevelDialog').show();
    },
    cancelSecurityLevelDialog()  {
        this.$element('securityLevelDialog').close();
    },
    onSecurityLevelChange(e) {
        if (e.value != this.securityLevel) {
            this.logText += "securityLevel select: " + e.value + ".\r\n";
            switch(e.value) {
                case '0':
                    this.securityLevel = data_distributedData.SecurityLevel.NO_LEVEL;
                    break;
                case '1':
                    this.securityLevel = data_distributedData.SecurityLevel.S0;
                    break;
                case '2':
                    this.securityLevel = data_distributedData.SecurityLevel.S1;
                    break;
                case '3':
                    this.securityLevel = data_distributedData.SecurityLevel.S2;
                    break;
                case '5':
                    this.securityLevel = data_distributedData.SecurityLevel.S3;
                    break;
                case '6':
                    this.securityLevel = data_distributedData.SecurityLevel.S4;
                    break;
                default:
                    this.securityLevel = data_distributedData.SecurityLevel.NO_LEVEL;
            }
        }
    },
    SubscribeType() {
        this.$element('subscribeTypeDialog').show();
    },
    cancelSubscribeTypeDialog() {
        this.$element('subscribeTypeDialog').close();
    },
    onSubscribeTypeChange(e){
        if (this.subscribeType != e.value) {
            this.logText += "SubscribeType select: " + e.value + ".\r\n";
            switch(e.value) {
                case '0':
                    this.subscribeType = data_distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL;
                    break;
                case '1':
                    this.subscribeType = data_distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE;
                    break;
                case '2':
                    this.subscribeType = data_distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL;
                    break;
                default:
                    this.subscribeType = data_distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE;
            }
        }
    },
    RegDataChange () {
        console.info("[JSDemo] RegDataChange begin");
        if(kvStore == null) {
            console.info('[JSDemo] RegDataChange kvStore is null');
            this.logText += "RegDataChange kvStore is null.\r\n";
            return;
        }
        if (!this.dataListenerStarted) {
            this.startDataListener();
            this.logText += "Register dataChange callback success.\r\n";
        } else {
            this.logText += "DataChange callback already registed.\r\n";
        }
    },
    RegSyncComplete () {
        console.info("[JSDemo] RegSyncComplete begin");
        if(kvStore == null) {
            console.info('[JSDemo] RegSyncComplete kvStore is null');
            this.logText += "RegSyncComplete kvStore is null.\r\n";
            return;
        }
        if (!this.syncListenerStarted) {
            this.startSyncListener();
            this.logText += "Register syncComplete callback success.\r\n";
        } else {
            this.logText += "SyncComplete callback already registed.\r\n";
        }
    },
    Put() {
        console.info("[JSDemo] Put begin");
        if(kvStore == null) {
            console.info('[JSDemo] Put kvStore is null');
            this.logText += "Put kvStore is null.\r\n";
            return;
        }
        try {
            const promise = kvStore.put('key_test_string', 'value_test_string');
            promise.then((data) => {
                console.log("[JSDemo] Put success " + data);
                this.logText += "Put success.\r\n";
            }).catch((err) => {
                console.log("[JSDemo] Put fail " + err);
                this.logText += "Put fail " + err + ".\r\n";
            });
        } catch (e) {
            console.log("[JSDemo] Put err " + e);
            this.logText += "Put err " + e + ".\r\n";
        }
    },
    Get() {
        console.info("[JSDemo] Get begin");
        if(kvStore == null) {
            console.info('[JSDemo] Get kvStore is null');
            this.logText += "Get kvStore is null.\r\n";
            return;
        }
        try {
            const promise1 = kvStore.get('key_test_string');
            promise1.then((data) => {
                console.log("[JSDemo] Get success " + data);
                this.logText += ("Get success. data:" + data + "\r\n");
            }).catch((err) => {
                console.log("[JSDemo] Get fail " + err);
                this.logText += "Get fail " + err + ".\r\n";
            });
        }catch (e){
            console.log("[JSDemo] Get err " + e);
            this.logText += "Get err " + e + ".\r\n";
        }
    },
    Delete() {
        console.info("[JSDemo] Delete begin");
        if(kvStore == null) {
            console.info('[JSDemo] Delete kvStore is null');
            this.logText += "Delete kvStore is null.\r\n";
            return;
        }
        try {
            const promise1 = kvStore.delete('key_test_string');
            promise1.then((data) => {
                console.log("[JSDemo] Delete success ");
                this.logText += "Delete success.\r\n";
            }).catch((err) => {
                console.log("[JSDemo] Delete fail " + err);
                this.logText += "Delete fail " + err + ".\r\n";
            });
        } catch(e) {
            console.log("[JSDemo] Delete err " + e);
            this.logText += "Delete err " + e + ".\r\n";
        }
    },
    SyncMode() {
        this.$element('syncModeDialog').show();
    },
    cancelSyncModeDialog() {
        this.$element('syncModeDialog').close();
    },
    onSyncModeChange(e){
        if (e.value != this.syncMode) {
            this.logText += "syncMode select: " + e.value + ".\r\n";
            switch(e.value) {
                case '0':
                    this.syncMode = data_distributedData.SyncMode.PULL_ONLY;
                    break;
                case '1':
                    this.syncMode = data_distributedData.SyncMode.PUSH_ONLY;
                    break;
                case '2':
                    this.syncMode = data_distributedData.SyncMode.PUSH_PULL;
                    break;
                default:
                    this.syncMode = data_distributedData.SyncMode.PUSH_ONLY;
            }
        }
    },
    Sync() {
        console.info("[JSDemo] Sync begin");
        if(kvStore == null) {
            console.info('[JSDemo] Sync kvStore is null');
            this.logText += "Sync kvStore is null.\r\n";
            return;
        }
        this.GetDevList();
        if(this.deviceList.length == 0) {
            console.info('[JSDemo] Sync deviceList is null');
            this.logText += "Sync deviceList is null.\r\n";
            return;
        }
        var devices = this.deviceList;
        //        var devices = ['15F21F503830418064542AA40C4D39FBE6BD3B7F143B35718F484D4AEAA42CE5']; //222
        //        var devices = ['A12C1F9261528B21F95778D2FDC0B2E33943E6251AC5487F4473D005758905DB']; //111
        var mode = this.syncMode;
        console.info('[JSDemo] Sync start');
        this.logText += "Sync" + devices + " SyncMode:" + mode + ".\r\n";
        kvStore.sync(devices, data_distributedData.SyncMode.PUSH_ONLY);
        this.logText += "Sync success.\r\n";
    },
    ClearLog() {
        this.logText = '';
    },
    print(list, name) {
        if (list != null) {
            for(var i = 0; i < list.length; i++) {
                console.info('[JSDemo] dataChange ' + name + ' key: ' + list[i].key + ' value: ' + list[i].value.value + ' type: ' + list[i].value.type);
                this.logText += (name + ' key: ' + list[i].key + ' value: ' + list[i].value.value + ' type: ' + list[i].value.type + ".\r\n");
            }
        }
    },
    printChangeData(notification) {
        var change = 'I(' + notification.insertEntries.length + ') U(' + notification.updateEntries.length +
        ') D(' + notification.deleteEntries.length + ') deviceId:' + notification.deviceId;
        console.info('[JSDemo] dataChange ' + change);
        this.logText += ("dataChange: " + change + ".\r\n");
        var inserts = notification.insertEntries;
        this.print(inserts, 'inserts');
        var deletes = notification.deleteEntries;
        this.print(deletes, 'deletes');
        var updates = notification.updateEntries;
        this.print(updates, 'updates');
    },
    startDataListener(){
        console.info("[JSDemo] startDataListener begin");
        let that = this;
        if(kvStore == null) {
            console.info('[JSDemo] startDataListener kvstore is null');
            return;
        }
        try {
            this.logText += "register dataChange SubscribeType:" + this.subscribeType + ".\r\n";
            kvStore.on('dataChange', parseInt(this.SubscribeType), function (data) {
                console.info('[JSDemo] dataChange callback call' + data);
                that.logText += "dataChange callback call.\r\n";
                if(data) {
                    that.printChangeData(data);
                }
            });
            this.dataListenerStarted = true;
        }catch(e) {
            console.info("[JSDemo] startDataListener err " + e);
            this.dataListenerStarted = false;
        }
    },
    stopDataListener(){
        console.log("[JSDemo] stopDataListener");
        this.dataListenerStarted = false;
    },
    startSyncListener(){
        console.info("[JSDemo] startSyncListener begin");
        let that = this;
        if(kvStore == null) {
            console.info('[JSDemo] startSyncListener kvstore is null');
            return;
        }
        try {
            kvStore.on('syncComplete', function (data) {
                console.info('[JSDemo] syncComplete callback call ' + data);
                that.logText += "syncComplete callback call.\r\n";
                if(data) {
                    that.logText += (data + ".\r\n");
                }
            });
            this.syncListenerStarted = true;
        }catch(e) {
            console.info("[JSDemo] startSyncListener err " + e);
            this.syncListenerStarted = false;
        }
    },
    stopSyncListener(){
        console.log("[JSDemo] stopSyncListener");
        this.syncListenerStarted = false;
    },
}
